/**
* @Author: 李晨光
* @Date: 2019/12/16
* @Version: 1.0
* @Last Modified by: 李晨光
* @Last Modified time: 2019/12/16
**/
<comment>
  # 行为观察
</comment>
<template>
  <div id="Observations" class="p-box">
    <div class="p-return">
      <mu-appbar color="primary" class="lan-header">
        <mu-button icon slot="left" v-close>
          <i class="iconfont angle-left iconangle-left"></i>
          <span class="lan-header-back">返回</span>
        </mu-button>行为观察
        <mu-button slot="right" icon @click="scanCode">
          <i class="iconfont iconsaoma"></i>
        </mu-button>
      </mu-appbar>
    </div>
    <div class="p-content" style="background:#fff">
      <div class="dim-search" style="padding-bottom:0.05rem">
        <input
          type="text"
          v-model="params.nameOrEmpNo"
          ref="searchInput"
          class="search-input"
          placeholder="请输入被观察人姓名/工号"
          @input="search"
        />
        <div class="searchList-container" v-if="params.nameOrEmpNo && people.length && !id">
          <ul class="search-list">
            <li
              v-for="(item,index) in people"
              :class="item.item.userId==nowUserId?'active':''"
              :key="'user'+index"
              @click="selectedPeople(item)"
            >
              <span>{{item.value}}</span>
            </li>
          </ul>
        </div>
      </div>
      <mu-container ref="container" class="lan-loadmore-content no-padding" style="flex:1">
        <template v-if="form.userId">
          <div class="lan-detail-list">
            <span class="lan-detail-h">姓名</span>
            <span class="lan-detail-r">{{obsUser.userName}}</span>
          </div>
          <div class="lan-detail-list">
            <span class="lan-detail-h">工号</span>
            <span class="lan-detail-r">{{obsUser.employeeNum}}</span>
          </div>
          <div class="lan-detail-list">
            <span class="lan-detail-h">项目</span>
            <span class="lan-detail-r">{{obsUser.orgName}}</span>
          </div>
          <div class="lan-detail-list" v-if="obsUser.unitName && obsUser.userType == '2'" >
            <span class="lan-detail-h">单位</span>
            <span class="lan-detail-r">{{obsUser.unitName}}</span>
          </div>
        </template>
        <mu-form
          :model="form"
          class="mu-lan-form"
          :label-position="'left'"
          label-width
          style="margin-top: 1px;"
        >
          <mu-form-item label="质量工匠行为" class="form-between required">
            <mu-flex class="select-control-row">
              <mu-radio
                :disabled="id ? true : false"
                style="margin-right: 10px"
                :key="mode.value"
                v-for="mode in modes"
                :value="mode.value"
                v-model="form.mode"
                @change="tabMode"
                :label="mode.label"
              ></mu-radio>
            </mu-flex>
          </mu-form-item>
          <template v-if="form.mode == '1'">
            <mu-form-item label="工匠行为" class="form-between">
              <mu-select
                :disabled="id && form.mode == '0' ? true : false"
                v-model="form.starScoreId"
                @change="behaviorChange"
                placeholder="请选择工匠行为"
                popover-class="lan-popover-select"
              >
                <mu-option
                  v-for="(behavior,index) in behaviors"
                  :key="index"
                  :label="behavior.name"
                  :value="behavior.id"
                ></mu-option>
              </mu-select>
              <i class="iconfont angle-left iconangle-right"></i>
            </mu-form-item>
            <mu-form-item label="奖励积分" class="form-between">
              <mu-text-field v-model="form.score" disabled placeholder="请输入奖励积分" :rows="1"></mu-text-field>
            </mu-form-item>
          </template>
          <template v-else>
            <mu-form-item label="工匠行为" class="form-between required">
              <mu-text-field
                :disabled="id ? true : false"
                v-model="form.behaviorName"
                placeholder="请输入工匠行为"
              ></mu-text-field>
            </mu-form-item>
            <mu-form-item label="奖励积分" class="form-between required">
              <mu-text-field v-model="form.score" placeholder="请输入奖励积分" :rows="1"></mu-text-field>
            </mu-form-item>
          </template>
          <mu-form-item label="现场照片" class="inline-item required">
            <div class="ly_flex ly_flex_wrap_wrap">
              <div
                style="position: relative;width: .7rem;height: .7rem;margin-right: .095rem;margin-bottom: .08rem;border-radius:0.02rem;background:rgba(216,216,216,1);overflow: hidden"
                v-for="(url, index) in handurl(form.scenePhotos)"
                :key="index"
              >
                <img
                  :src="url"
                  style="transform: scale(1.5)"
                  @click="open('imgPreview',{url: url})"
                  alt
                />
                <i
                  class="iconfont iconqingchu"
                  @click.stop="delImg(form, url)"
                  style="color: #FF4242;position: absolute;right: .05rem; top: 0;"
                  v-if="!id"
                ></i>
              </div>
              <div
                style="margin: 0 .1rem .14rem 0;"
                v-if="!id && handurl(form.scenePhotos).length < 5"
              >
                <FileUpload @successed="confirm('imgUpload',{res: $event, form})"></FileUpload>
              </div>
            </div>

            <!-- <mt-switch v-model="form.useTable"></mt-switch> -->
          </mu-form-item>
          <mu-form-item label="备注" class="inline-item">
            <mu-text-field
              :disabled="id ? true : false"
              v-model="form.remark"
              multi-line
              placeholder="请输入"
              :rows="4"
              :rows-max="8"
            ></mu-text-field>
          </mu-form-item>

          <mu-form-item label="审核人" class="inline-item required" style="padding-bottom: 10px">
            <div class="userBox" v-for="(user, index) in form.reviewUsers" :key="index">
              <div
                class="ly_flex ly_flex_just_center ly_flex_ali_center add"
              >{{user.label.substr(0,1)}}</div>
              <span>{{user.label}}</span>
              <i
                class="iconfont iconqingchu"
                @click.stop="delUser('reviewUser',form, user.value)"
                style="color: #FF4242;position: absolute;right: .05rem; top: 0;"
                v-if="!id"
              ></i>
            </div>
            <div style v-if="!id" @click="open('user', {form, type: 'reviewUser'})">
              <div class="userTrigger" @click="sheetVisible = true">
                <div class="ly_flex ly_flex_just_center ly_flex_ali_center add">
                  <i class="iconfont iconplus"></i>
                </div>
                <span>添加人员</span>
              </div>
            </div>
          </mu-form-item>
        </mu-form>
        <div style="padding:0 14px;">
          <mu-button full-width color="primary" style="margin:.2rem 0" @click="save">提交</mu-button>
        </div>
      </mu-container>
    </div>
    <!-- <div style="height:calc(100vh - .45rem);overflow: auto;background: #fff;" class="history">
     
    </div>-->
    <!-- 选人 -->
    <User
      ref="User"
      v-if="user.open"
      :open="user.open"
      :multiple="user.multiple"
      :orgType="user.userType"
      :dataScope="'org-project'"
      @close="close('user')"
      v-model="user.res"
      @confirm="confirm('user')"
    ></User>
  </div>
</template>

<script>
import debounce from "lodash.debounce";
import User from "@/select/user/User.vue";
import FileUpload from "@/fileUpload/FileUpload.vue";

export default {
  name: "Observations",
  components: {
    User,
    FileUpload
  },
  props: {},
  data() {
    return {
      api: {
        getBehaviorApi: "/safety/starScoreSet/list", // 获取工匠行为列表
        getUserMsgApi: "/safety/starObserve/userInfo", // 获取人员信息
        addObserveApi: "/safety/starObserve/add", // 行为观察提交
        getObsDetailApi: "/safety/starObserve/detail" // 获取详情
      },
      params: {
        nameOrEmpNo: "",
        userId: "",
        orgId: "",
        type: ""
      },
      nowUserId: "",
      // 人员选择
      user: {
        open: false,
        userType: "currOrgProject",
        res: [],
        type: "",
        multiple: true
      },
      // 图片预览
      imgPreview: {
        open: false,
        imgUrl: ""
      },
      // 图片上传
      imgUpload: {
        open: false
      },
      people: [],
      modes: [
        {
          label: "配置模式",
          value: "1"
        },
        {
          label: "自定义模式",
          value: "0"
        }
      ],
      behaviors: [],
      obsUser: {
        orgName: "房建项目",
        userName: "董兆民",
        unitName: "测试2(南京公司)",
        employeeNum: "501A0586"
      },
      form: {
        userId: "",
        orgId: "",
        starScoreId: "",
        mode: "0",
        behaviorName: "",
        score: "",
        scenePhotos: "",
        remark: "",
        approvalUserId: "",
        reviewUsers: []
      },
      id: "", // 编辑用
      detail: {}
    };
  },
  computed: {},
  created() {
    let orgInfo = this.$A.GS("orgInfo");
    let userInfo = this.$A.GS("userInfo");
    this.params.orgId = orgInfo.orgId;
    this.params.type = orgInfo.type;
    // this.params.userId = userInfo.userId
    this.getBehavior();
    this.id = this.$route.query.id;
    if (this.id) {
      this.getDetailData(this.id);
    }
  },
  mounted() {},
  watch: {
    "params.nameOrEmpNo": {
      handler(val) {
        if (!val) {
          this.people = [];
        }
      },
      deep: true
    }
  },
  methods: {
    scanCode() {
      wx.ready(() => {
        wx.checkJsApi({
          jsApiList: ["invoke", "scanQRCode"], // 需要检测的JS接口列表，所有JS接口列表见附录2,
          success: ress => {
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
          }
        });
        wx.invoke("enterpriseVerify", {}, res => {
          // alert(JSON.stringify(res));
        });
        wx.scanQRCode({
          desc: "scanQRCode desc",
          needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
          scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是条形码（一维码），默认二者都有
          success: res => {
            // 回调
            this.$openLoading();
            let data = JSON.parse(res.resultStr);
            let params = {
              obj: {
                orgId: this.params.orgId, // 组织ID
                roleId: "",
                employeeNumber: data.userNumber, // 工号
                userName: ""
              },
              pageNo: 1,
              pageSize: 2
            };
            this.$A.Go("post", "/safety/org", params).then(response => {
              this.$closeLoading();
              console.log(response);
              if (
                response.code == 200 &&
                response.body &&
                response.body.length
              ) {
                this.obsUser = {
                  orgName: data.projecName,
                  userName: data.userName,
                  unitName: data.unitName ? data.unitName : "",
                  employeeNum: data.userNumber
                };
                this.form.orgId = data.projecId;
                this.form.userId = data.userId;
                this.nowUserId = data.userId;
                this.params.nameOrEmpNo = "";
                this.people = [];
              } else {
                this.$A.MS("无人员信息");
              }
            });
          },
          error: res => {
            if (res.errMsg.indexOf("function_not_exist") > 0) {
              alert("版本过低请升级");
            }
          }
        });
      });
    },
    // 获取详情
    getDetailData(id) {
      this.$openLoading();
      this.$A
        .Go("get", this.api.getObsDetailApi, {
          id: id
        })
        .then(response => {
          this.$closeLoading();
          Util.processRes(response, () => {
            this.detail = response.body;
            this.form = {
              userId: this.detail.userId,
              orgId: this.detail.orgId,
              starScoreId: this.detail.starScoreId,
              mode: this.detail.starScoreId ? "1" : "0",
              behaviorName: this.detail.behaviorName,
              score: this.detail.score,
              scenePhotos: this.detail.scenePhotos,
              remark: this.detail.remark,
              approvalUserId: this.detail.approvalUserId,
              reviewUsers: [{label:this.detail.approvalUserName,value:this.detail.approvalUserId}]
            };
            this.params.nameOrEmpNo = this.detail.beObservedUserName
            this.getUserMsg(this.detail.beObservedUserId);
          });
          Util.processError(this, response);
        })
        .catch(err => {
          this.$closeLoading();
          console.log(err);
        });
    },
    // 搜索
    search: debounce(function(val) {
      if(this.id){
        return;
      }
      this.getUserMsg();
    }, 1000),
    // 获取人员信息
    getUserMsg(isnot) {
      if (!this.params.nameOrEmpNo) {
        return;
      }
      this.$A
        .Go("get", this.api.getUserMsgApi, this.params)
        .then(response => {
          if (response.code == 200) {
            if (response.body.length) {
              if(isnot){
                let arr = response.body.filter(o=>o.userId == isnot)
                if(arr.length){
                  this.selectedPeople({value: arr[0]['userName'],item: arr[0]})
                }
                
              }else{
                let list = [];
                response.body.forEach(item => {
                  list.push({
                    value: item.userName + " " + item.employeeNum,
                    item: item
                  });
                });
                this.people = list;
              }
              
            } else {
              this.people = [];
            }
          }
        })
        .catch(err => {
          this.$closeLoading();
          console.log(err);
        });
    },
    selectedPeople(data) {
      this.params.nameOrEmpNo = data.value;
      this.obsUser = data.item;
      this.form.orgId = data.item.orgId;
      this.form.userId = data.item.userId;
      this.nowUserId = data.item.userId;
      this.people = [];
    },
    // 切换模式
    tabMode() {
      if (this.form.mode == "1") {
        this.getBehavior();
      } else {
      }
    },
    // 获取工匠行为
    getBehavior() {
      this.$A
        .Go("get", this.api.getBehaviorApi, {
          orgId: this.params.orgId,
          type: this.params.type
        })
        .then(response => {
          Util.processRes(response, () => {
            this.behaviors = response.body;
          });
          Util.processError(this, response);
        })
        .catch(err => {
          this.$closeLoading();
          console.log(err);
        });
    },
    // 行为切换
    behaviorChange() {
      if (this.form.starScoreId) {
        this.form.score = this.behaviors.find(
          i => i.id == this.form.starScoreId
        ).score;
      }
    },
    // 组件打开
    open(type, props = {}) {
      switch (type) {
        // 人员
        case "user":
          this.user.res = [];
          this.pointTemp = props.form;
          this.user.type = props.type;
          if (this.user.type == "reviewUser") {
            this.user.multiple = false;
            this.user.res = props.form.reviewUsers || [];
          }
          this.user.open = true;
          break;
        // 图片预览
        case "imgPreview":
          this.imgPreview.imgUrl = props.url;
          this.imgPreview.open = true;
          break;
        // 图片上传
        case "imgUpload":
          this.imgUpload.oen = true;
          break;
      }
    },
    // 组件弹窗关闭
    close(type, props = {}) {
      switch (type) {
        // 人员
        case "user":
          this.user.open = false;
          break;
        // 图片预览
        case "imgPreview":
          this.imgPreview.open = false;
          break;
        // 图片上传
        case "imgUpload":
          this.imgUpload.oen = false;
          break;
      }
    },
    // 结果确认
    confirm(type, props) {
      switch (type) {
        // 人员
        case "user":
          this.user.open = false;
          this.addUser(this.user.type);
          break;
        // 图片预览
        case "imgPreview":
          this.imgPreview.open = false;
          break;
        // 图片上传
        case "imgUpload":
          this.addImg(
            props.form,
            this.$A.baseUrl[0] +
              "/safety/system/download?fileUrl=" +
              props.res.body
          );
          this.imgUpload.open = false;
          break;
      }
    },
    handurl(str) {
      if (!str) {
        return [];
      } else {
        return str.split(",");
      }
    },
    // 添加人员
    addUser(type) {
      let ids = [];
      this.user.res.forEach(u => {
        if (!ids.includes(u.value)) {
          ids.push(u.value);
        }
      });
      switch (type) {
        case "reviewUser":
          this.form.reviewUsers = this.user.res;
          this.form.approvalUserId = ids.join(",");
          break;
      }
    },
    // 删除人员
    delUser(type, form, id) {
      let ids = [];
      switch (type) {
        // 复查人
        case "reviewUser":
          form.reviewUsers.splice(
            form.reviewUsers.findIndex(i => i.value == id),
            1
          );
          this.$forceUpdate();
          form.reviewUsers.forEach(u => {
            if (!ids.includes(u.value)) {
              ids.push(u.value);
            }
          });
          form.approvalUserId = ids.join(",");
          break;
      }
    },
    // 添加照片
    addImg(form, url) {
      let arr = this.handurl(form.scenePhotos);
      arr.push(url);
      form.scenePhotos = arr.join(",");
      // this.$forceUpdate()
    },
    // 删除照片
    delImg(form, url) {
      let arr = this.handurl(form.scenePhotos);
      arr.splice(arr.indexOf(url), 1);
      form.scenePhotos = arr.join(",");
    },
    // 验证表单
    validateForm() {
      if (!this.form.userId) {
        this.$A.MS(`请选择被观察人`);
        return false;
      }
      if (this.form.mode == "1") {
        if (!this.form.starScoreId) {
          this.$A.MS(`请选择工匠行为`);
          return false;
        }
      } else {
        if (!this.form.behaviorName) {
          this.$A.MS(`请填写工匠行为`);
          return false;
        }
        if (!this.form.score) {
          this.$A.MS(`请填写奖励积分`);
          return false;
        }
      }
      if (!this.form.scenePhotos) {
        this.$A.MS(`请添加现场照片`);
        return false;
      }

      if (!this.form.approvalUserId) {
        this.$A.MS(`请选择审核人`);
        return false;
      }
      return true;
    },
    // 保存
    save() {
      if (this.validateForm()) {
        let arr = [
              "userId",
              "approvalUserId",
              "behaviorName",
              "orgId",
              "remark",
              "scenePhotos",
              "score",
              "starScoreId"
            ]
        // if(this.id){
        //   this.form['id'] = this.id
        //   arr.push('id')
        // }
        this.$A
          .Go(
            "post",
            this.api.addObserveApi,
            Util.delParams(this.form, arr)
          )
          .then(response => {
            Util.processRes(response, () => {
              this.$A.MS(`提交成功`);
              this.$router.back();
            });
            Util.processError(this, response);
          })
          .catch(err => {
            this.$closeLoading();
            console.log(err);
          });
      }
    }
  },
  destroyed() {}
};
</script>

<style lang="scss">
#Observations {
  .p-content {
    display: flex;
    flex-direction: column;
  }
  .imgTrigger {
    height: 0.75rem;
    width: 0.75rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .userTrigger {
    height: 0.75rem;
    width: 0.6rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #0080cb;
    .add {
      border-radius: 0.25rem;
      width: 0.5rem;
      height: 0.5rem;
      border: 0.01rem solid rgba(0, 128, 203, 1);
    }
  }
  .userBox {
    margin-top: 4px;
    position: relative;
    height: 0.75rem;
    width: 0.6rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #0080cb;
    border-radius: 0.02rem;
    overflow: hidden;
    color: rgba(61, 61, 61, 1);
    .add {
      border-radius: 0.25rem;
      width: 0.5rem;
      height: 0.5rem;
      font-size: 0.26rem;
      color: #fff;
      background: rgba(0, 128, 203, 1);
      border: 0.01rem solid rgba(0, 128, 203, 1);
    }
  }
}
</style>
